package com.fuxinglianbao.services;

import com.fuxinglianbao.models.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.persistence.EntityManager;
import java.time.LocalDateTime;

@Service
public class UserService {
    @Autowired
    private EntityManager entityManager;

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Transactional
    public User register(String phone, String password, String referrerPhone) {
        // 验证手机号是否已注册
        if (findByPhone(phone) != null) {
            throw new IllegalArgumentException("该手机号已注册");
        }

        User user = new User();
        user.setPhone(phone);
        user.setPassword(passwordEncoder.encode(password));

        // 设置推荐人
        if (referrerPhone != null) {
            User referrer = findByPhone(referrerPhone);
            if (referrer == null) {
                throw new IllegalArgumentException("推荐人不存在");
            }
            user.setReferrer(referrer);
        }

        entityManager.persist(user);
        return user;
    }

    @Transactional(readOnly = true)
    public User findByPhone(String phone) {
        return entityManager.createQuery(
                "SELECT u FROM User u WHERE u.phone = :phone", User.class)
                .setParameter("phone", phone)
                .getResultStream()
                .findFirst()
                .orElse(null);
    }

    @Transactional
    public User login(String phone, String password) {
        User user = findByPhone(phone);
        if (user == null || !passwordEncoder.matches(password, user.getPassword())) {
            throw new IllegalArgumentException("手机号或密码错误");
        }

        user.setLastLoginTime(LocalDateTime.now());
        entityManager.merge(user);
        return user;
    }

    @Transactional
    public User updateProfile(Long userId, String nickname, String avatar) {
        User user = entityManager.find(User.class, userId);
        if (user == null) {
            throw new IllegalArgumentException("用户不存在");
        }

        if (nickname != null) {
            user.setNickname(nickname);
        }
        if (avatar != null) {
            user.setAvatar(avatar);
        }

        return entityManager.merge(user);
    }

    @Transactional(readOnly = true)
    public User getUser(Long userId) {
        User user = entityManager.find(User.class, userId);
        if (user == null) {
            throw new IllegalArgumentException("用户不存在");
        }
        return user;
    }
}